﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.Client;
using System.Collections.ObjectModel;
using Microsoft.TeamFoundation.Framework.Client;
using Microsoft.TeamFoundation.Framework.Common;

namespace TrelloTFSBridge
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            string publicBoard = "4d5ea62fd76aa1136000000c";
            string testBoard = "50e4beb2c8a314f82b002701";
            Trello trello = new Trello();
            trello.applicationKey = "a1220431114565d1d22aced53269bcdf";
            trello.applicationName = "Trello-TFS Bridge";
            trello.secret="3d9ee90b4a5677becf0f173e37fc094cc3a8c2f5714de6ed1c4309a664ddd23f";//for oAuth signing
            var obj = trello.GetBoard(publicBoard);
            //trello.GetToken();
            //var obj2 = trello.GetBoard(testBoard);
            ConnectToTFS();
        }
        static void ConnectToTFS()
        {
            var credentials = new System.Net.NetworkCredential("snd\\mirhagk_cp", "");
            // Connect to Team Foundation Server
            //     Server is the name of the server that is running the application tier for Team Foundation.
            //     Port is the port that Team Foundation uses. The default port is 8080.
            //     VDir is the virtual path to the Team Foundation application. The default path is tfs.
            Uri tfsUri =
                new Uri("https://tfs.codeplex.com/tfs/tfs13");
            tfsUri = new Uri("http://tfs.phri.ca:8080/tfs");
            tfsUri = new Uri("https://eldidip.visualstudio.com:8080/tfs");

            TfsConfigurationServer configurationServer = //new TfsConfigurationServer(tfsUri, credentials);
                TfsConfigurationServerFactory.GetConfigurationServer(tfsUri);
            
            //configurationServer = new TfsConfigurationServer(tfsUri, credentials);

            //configurationServer.Authenticate();

            // Get the catalog of team project collections
            ReadOnlyCollection<CatalogNode> collectionNodes = configurationServer.CatalogNode.QueryChildren(
                new[] { CatalogResourceTypes.ProjectCollection },
                false, CatalogQueryOptions.None);

            // List the team project collections
            foreach (CatalogNode collectionNode in collectionNodes)
            {
                // Use the InstanceId property to get the team project collection
                Guid collectionId = new Guid(collectionNode.Resource.Properties["InstanceId"]);
                TfsTeamProjectCollection teamProjectCollection = configurationServer.GetTeamProjectCollection(collectionId);

                // Print the name of the team project collection
                Console.WriteLine("Collection: " + teamProjectCollection.Name);

                // Get a catalog of team projects for the collection
                ReadOnlyCollection<CatalogNode> projectNodes = collectionNode.QueryChildren(
                    new[] { CatalogResourceTypes.TeamProject },
                    false, CatalogQueryOptions.None);

                // List the team projects in the collection
                foreach (CatalogNode projectNode in projectNodes)
                {
                    Console.WriteLine(" Team Project: " + projectNode.Resource.DisplayName);
                }
            }
        }
    }
    class Trello
    {
        public string applicationKey { get; set; }
        public string applicationName { get; set; }
        public string secret { get; set; }
        public string userToken { get; set; }
        public class Board
        {
            public string id { get; set; }
            public string name { get; set; }
            public string desc { get; set; }
            public bool closed { get; set; }
            public string idOrganization { get; set; }
            public string pinned { get; set; }
            public string url { get; set; }
            public Prefs prefs { get; set; }

            public class Prefs
            {
                public string permissionLevel { get; set; }
                public string voting { get; set; }
                public string comments { get; set; }
                public string invitations { get; set; }
                public bool selfJoin { get; set; }
                public bool cardCovers { get; set; }
            }

        }
        public Board GetBoard(string boardID)
        {
            var client = new System.Net.WebClient();
            string address = String.Format("https://api.trello.com/1/board/{0}?key={1}{2}", boardID, applicationKey, String.IsNullOrWhiteSpace(userToken) ? "" : "&token=" + userToken);
            string result= client.DownloadString(address);

            var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
            return jss.Deserialize<Board>(result);
        }
        public void GoToWebsiteForToken(int expiration = 30, bool writeAble = false)
        {
            string expirationString = expiration.ToString() + "days";
            string address = String.Format("https://trello.com/1/authorize?key={0}&name={1}&expiration={2}&response_type=token&scope=read{3}",
                applicationKey, applicationName, expirationString, writeAble ? "write" : "");
            System.Diagnostics.Process.Start(address);
        }
        public void GetToken(int? expiration = null, bool? writeable = null)
        {
            Console.WriteLine("Press enter to open the browser and give this application permission. Copy the token to the clipboard and this program will automagically grab it");
            Console.ReadKey();
            if (expiration == null && writeable == null)
                GoToWebsiteForToken();
            else if (writeable == null)
                GoToWebsiteForToken(expiration: (int)expiration);
            else if (expiration == null)
                GoToWebsiteForToken(writeAble: (bool)writeable);
            else
                GoToWebsiteForToken((int)expiration, (bool)writeable);
            
            //copy the existing value from the clipboard and store it so that we can restore it later, just to be nice
            var preItem = System.Windows.Forms.Clipboard.GetDataObject();
            System.Windows.Forms.Clipboard.Clear();//clear the clipboard

            while (!System.Windows.Forms.Clipboard.ContainsText()) System.Threading.Thread.Sleep(100);//keep waiting until the clipboard actually has text in it
            userToken = System.Windows.Forms.Clipboard.GetText();//grab the token
            System.Windows.Forms.Clipboard.SetDataObject(preItem);//reset the clipboard to the initial value
        }
            
    }
    
}
